package com.ash.dao.imp;

import com.ash.dao.IUserDao;
import com.ash.entity.User;
import com.ash.util.ConnectionsUtil;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : Chen Chao
 * @encoding : UTF-8
 * @date : 2020/12/28 15:31
 * @file : test06.com.ash.dao.imp.IUserDaoImpl.java
 * @software : IntelliJ IDEA
 * @since : 1.8
 */
public class UserDaoImpl implements IUserDao {
    protected  QueryRunner qr = new QueryRunner(ConnectionsUtil.getDataSource());
    @Override
    public List<User> getSpecifiedUser(Integer id, String userName) {
        StringBuilder sql=new StringBuilder("select * from user  u,role  r where u.userRole=r.id");
        /*获取信息*/
        List<User> userList=null;
        ArrayList<Object> objects = new ArrayList<>();
        /*由于参数个数不确定，封装成ArrayList*/
        /*初始为空，查所有*/
        if(id!=null){
            System.out.println(id);
            objects.add(id);
            sql.append(" and r.id=?");
        }
        /*利用工具类判断字符串不为null不为“”*/
        if(!StringUtils.isNullOrEmpty(userName)){
            System.out.println(userName);
            userName="%"+userName+"%";
            objects.add(userName);
            sql.append(" and u.userName like ?");
        }
        System.out.println(sql);
        /*执行查询操作*/
        try {
            userList = qr.query(String.valueOf(sql), new BeanListHandler<>(User.class),objects.toArray());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return userList;
    }


}
